package servlets;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.ads.tpgrupo4.server.service.listaDePrecios.NuevaListaDePreciosService;
import com.ads.tpgrupo4.server.xml.InputStreamXmlSource;
import com.ads.tpgrupo4.server.xml.XmlSource;

@WebServlet("/NuevaListaDePreciosService")
@MultipartConfig
public class NuevaListaDePreciosServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private NuevaListaDePreciosService nuevaListaDePreciosService = NuevaListaDePreciosService.getInstance();
	
	public NuevaListaDePreciosServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		 final Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
		 final String fileName = getFileName(filePart);
		 final InputStream inputStream = filePart.getInputStream();
		 
		 final XmlSource listaDePreciosXmlSource = new InputStreamXmlSource(inputStream);
		 this.nuevaListaDePreciosService.nuevaListaDePrecios(listaDePreciosXmlSource);
		 
		 response.setContentType("text/html");
			java.io.PrintWriter out = response.getWriter();
			out.println(
					"<!DOCTYPE html>\n"+
							"<html>\n"+
							"<head><title>Response</title></head>"+
							"<h3>Received file OK: " + fileName + "</h3>"+
							"</html>"
					);
	}
	
	private static String getFileName(final Part part) {
	    for (String cd : part.getHeader("content-disposition").split(";")) {
	        if (cd.trim().startsWith("filename")) {
	            String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
	            return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
	        }
	    }
	    return null;
	}
	
}
